<?php

class User extends CI_Controller{

	function __construct()
	{
		parent::__construct();
		$this->load->model(array('admin/auth_model','user_model'));
		$this->load->library('form_validation');
	}
	
	function login()
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			$username	=	$this->input->post('username');
			$pass		=	md5($this->input->post('password'));
			
			$user	=	$this->auth_model->login($username,$pass);
			if($user)
			{
				redirect(base_url());
			}
			else{
				//die('+++');
			}
		}
		$this->data['tpl_file']		=	'user/login';
		$this->load->view('user/login', $this->data);
	}
	
	function logout()
	{
		session_destroy();
		redirect(base_url());
	}
	
	function my_account()
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			
			if($this->input->post('o_password') != '' && $this->input->post('new_password') && $this->input->post('c_password'))
			{
				$this->form_validation->set_rules('o_password','Old Password','required|callback__check_password');
				$this->form_validation->set_rules('new_password','New Password','required|matches[c_password]');
				$this->form_validation->set_rules('c_password','Confirm Password','required');
				if($this->form_validation->run() == TRUE){
					$data	=	array(
						'password'	=>	md5($this->input->post('new_password')),
						'email'		=>	$this->input->post('email')
					);
					$this->user_model->update($_SESSION['_user']['user_id'],$data);
					redirect(base_url().'login/');
				}
			}
		}
		$this->load->view('user/my_account');
	}
	
	function _check_password($password = '')
	{
		if(!$this->user_model->get_by(array('username' => $_SESSION['_user']['username'],'password' => md5($password))))
		{
			$this->form_validation->set_message('_check_password','The %s is incorrect!');
			return FALSE;
		}
		return TRUE;
	}
}